<?php
session_start();
require 'util.php';
checkLoggedIn();

if(isset($_POST['action']) && $_POST['action'] != ""){
	$action = $_POST['action'];
	switch ($action) {
	case 'save':
		saveListing($_POST, $_FILES);
		break;
	
	default:
		# code...
		break;
	}
}else if(!isLoggedIn()){
	goToUrl($GLOBALS['loginPageUrl']);
}


function listingExists($user){
	$result = getListing($user);
	return !empty($result);
}

function getListing($user){
	$query = "SELECT result.*, address.postcode AS 'postcode',
	address.pk AS 'addressPk',
	 address.street AS 'street',
	  address.district AS 'district',
	   address.city AS 'city',
	    address.house AS 'house',
	     location.latitude AS 'lat',
	     location.pk AS 'locationPk',
	      location.longitude AS 'lng' FROM result INNER JOIN address ON result.address_fk = address.pk INNER JOIN location ON address.location_fk = location.pk WHERE user_fk = :user_fk";
	$params = array(
		":user_fk"=>$user
		);
	$result = getResultArray($query, getPdo(), $params);
	return $result;
}

function saveListing($post, $files){
	$pdo = $GLOBALS['pdo'];
	$pk = $post['exant'];
	$isUpdate = $pk != "";
	try{
		$pdo->beginTransaction();
		$paramsCoords = array(
			":latitude"=>$post['lat'],
			":longitude"=>$post['lng']
			);
		if($isUpdate){
			$paramsWhere = array(
				":pk"=>$post['exantLocation']
				);
			$locationFk = executeUpdate("location", $paramsCoords, $paramsWhere, $pdo);
		}else{
			$locationFk = executeInsert("location", $paramsCoords, $pdo);
		}
		
		$paramsAddress = array(
			":postcode"=>$post['postcode'],
			":street"=>$post['street'],
			":district"=>$post['area'],
			":city"=>$post['city'],
			":house"=>$post['houseNumber'],
			":location_fk"=>$locationFk
			);
		if($isUpdate){
				$paramsWhere = array(
				":pk"=>$post['exantAddress']
				);
			unset($paramsAddress[":location_fk"]);
			$addressFk = executeUpdate("address", $paramsAddress, $paramsWhere, $pdo);
		}else{
			$addressFk = executeInsert("address", $paramsAddress, $pdo);
		}
		$params = array(
			":title"=> $post['name'],
			":image_url"=> "",
			":description"=> $post['description'],
			":price"=> $post['price'],
			":user_fk"=> $post['user'],
			":result_type_fk"=> $post['typeofListing'],
			":telephone"=> $post['telephone'],
			":email"=> $post['email'],
			":webpage"=> $post['webpage'],
			":room_type_fk"=> $post['roomType'],
			":bed_type_fk"=> $post['bedType'],
			":accomodates"=> $post['accomodates'],
			":bedrooms"=> $post['bedrooms'],
			":beds"=> $post['beds'],
			":extra_people"=> $post['extraPeople'],
			":week_price"=> $post['weekPrice'],
			":month_price"=> $post['monthPrice'],
			":cancellation_fee"=> $post['cancellationFee'],
			":rules"=> $post['typeofListing'] == "1" ? $post['rulesHouse'] : ($post['typeofListing'] == "2" ? $post['rulesHotel'] : ""),
			":cancellation_type_fk"=> $post['cancellation'],
			":address_fk"=> $addressFk,
			":rating"=> $post['rating']
			);
		if($isUpdate){
			$paramsWhere = array(
			":pk"=>$post['exant']
			);
			unset($params[":address_fk"]);
			executeUpdate("result", $params, $paramsWhere, $pdo);
		}else{
			$listingPk = executeInsert("result", $params, $pdo);
		}
		$dir = createDirectory("img/profiles/".getLoggedInUser()."/listing");
		$filePaths = moveFiles($files, $dir);
		if($filePaths && !empty($filePaths)){
			$params = array();
			$params[':image_url'] = $filePaths[0];
			$paramsWhere = array(
				":user_fk"=>getLoggedInUser()
				);
			executeUpdate("result", $params, $paramsWhere, $pdo);
		}
		$pdo->commit();
		goToUrl($GLOBALS['profilePage']);
	}catch(PDOException $e) {
		$pdo->rollback();
		echo $e;
		throw $e;
	}
}

function displayRoomTypes($type = ""){
	$rt = getListingRoomTypes();
  	foreach ($rt as $key => $value) {
  		$pk = $value['pk'];
  		$description = $value['description'];
  		if($type != "" && $type == $pk){
  			echo "<option value='$pk' selected>$description</option>";
		}
		else{
			echo "<option value='$pk'>$description</option>";
		}
  		
  	}
}

function displayBedTypes($type = ""){
	$rt = getListingBedTypes();	
	foreach ($rt as $key => $value) {
		$pk = $value['pk'];
		$description = $value['description'];
		if($type != "" && $type == $pk){
			echo "<option value='$pk' selected>$description</option>";
		}
		else{
			echo "<option value='$pk'>$description</option>";
		}
  		
  	}
}

function displayCancellationTypes($type = ""){
	$rt = getListingCancellationTypes();
	foreach ($rt as $key => $value) {
	  	$pk = $value['pk'];
		$description = $value['description'];
		if($type != "" && $type == $pk){
			echo "<option value='$pk' selected>$description</option>";
		}
		else{
			echo "<option value='$pk'>$description</option>";
		}
  	}
}

function displayListingCathegories($type = ""){
	$rt = getListingCathegories();
	foreach ($rt as $key => $value) {
		$pk = $value['pk'];
  		$description = $value['description'];
  		if($type != "" && $type == $pk){
  			echo "<option value='$pk' selected>$description</option>";
  		}else{
  			echo "<option value='$pk'>$description</option>";
  		}
  		
  	}	
}

function displayGenders($gender = ""){
	$rt = getGenders();
	foreach ($rt as $key => $value) {
		$pk = $value['pk'];
  		$description = $value['description'];
  		if($gender != "" && $gender == $pk){
  			echo "<input type=\"radio\" name=\"gender\" id=\"genderM\" value=\"$pk\" checked>$description</input>";
		}
		else{
			echo "<input type=\"radio\" name=\"gender\" id=\"genderM\" value=\"$pk\">$description</input>";
		}
  		
  	}	
}

function printSelected($field, $value){
	echo ($field != "" && $field == $value ? "selected":"");
}

?>